﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace IanUtil.Serialization
{
    public class IU_SL_JSON
    {
        public static object JSON2Object(string json, Type type)
        {
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            sw.Write(json);
            sw.Flush();
            ms.Position = 0;
            DataContractJsonSerializer sl = new DataContractJsonSerializer(type);
            object obj = sl.ReadObject(ms);
            sw.Close();
            return obj;
        }

        public static string Object2JSON(object obj)
        {
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer sl = new DataContractJsonSerializer(obj.GetType());
            sl.WriteObject(ms, obj);
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            string json = sr.ReadToEnd();
            sr.Close();
            return json;
        }
    }
}
